import pymysql

from tools.handle_ini import conf

class HandleDb:
    def __init__(self):
        mysql_info = dict(conf.items('mysql'))
        self.conn = pymysql.connect(host=mysql_info["host"],
                               port=int(mysql_info["port"]),
                               user=mysql_info["user"],
                               password=mysql_info["password"],
                               db=mysql_info["db"],
                               autocommit=True,
                               cursorclass=pymysql.cursors.DictCursor)
        self.cur = self.conn.cursor()

    # 获取一条数据
    def get_db_one_data(self,sql,args=None):
        self.cur.execute(sql,args)
        return self.cur.fetchone()

    # 获取全部数据
    def get_db_all_data(self,sql,args=None):
        self.cur.execute(sql,args)
        return self.cur.fetchall()

    # 关闭数据库连接
    def close(self):
        self.cur.close()
        self.conn.close()

# 使用单例模式，后续导入数据库就只导入mysql
mysql = HandleDb()

